package com.zzptc.shop.servlet;


import com.zzptc.shop.dao.IDAO;

import com.zzptc.shop.dao.ShopCarGood;
import com.zzptc.shop.vo.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "ShoppingServlet")
public class ShoppingServlet extends HttpServlet {
    List<ShopCarGood> carlist;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");

      // printWriter.print("**********");
    //1\获取ID
       int id=0;
        if(request.getParameter("id")!=null){
            String sid=request.getParameter("id");
            id=Integer.parseInt(sid);
        }
        //2、根据ID能查询该商品的详情
        IDAO dao=new GoodDaoImp();
//       ShopCarGood shopCarGood=((GoodDaoImp) dao).getGoodByID(id);
        Product shopCarGood1 = ((GoodDaoImp) dao).getGoodByID(id);
         //3、将商品添加购物车
        //购物车是什么？怎么实现将商品添加到同一台购物车，以免出现只出现最后的一个添加上的商品
        if (carlist==null){
            carlist=new ArrayList();
        }
        ShopCarGood Good=new ShopCarGood();
        Good.setId(shopCarGood1.getEp_id());
        Good.setName(shopCarGood1.getEp_name());
        Good.setPrice(shopCarGood1.getEp_price());
        shopCarGood1.setEp_file_name("");
        Good.setNum(1);

        //购物车
        // j将商品添加到购物车（如果第一次添加的话，add；如果不是第一次添加，就只要添加数目）
        ShopCarUtil.addGood(Good,carlist);
        //request.setAttribute("shop",carlist);
       // request.getRequestDispatcher("shopping.jsp").forward(request, response);
        //换一个作用域 域对象：  page  session application
        HttpSession se=request.getSession();
        se.setAttribute("shop",carlist);
        //跳转
        response.sendRedirect("shopping.jsp");

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
